﻿using System.Linq;
using Elasticsearch.Synchronize.Common.Enum;
using Elasticsearch.Synchronize.Domain.Events;
using Elasticsearch.Synchronize.Domain.Interface;

namespace Elasticsearch.Synchronize.DomainEventHandler.Handler
{
    public class TraverseRuleDataEventHandler : MediatR.NotificationHandler<TraverseRuleDataDomainEvent>
    {
        private readonly ISynchronizeItemRepository _itemRepository;

        public TraverseRuleDataEventHandler(ISynchronizeItemRepository itemRepository)
        {
            _itemRepository = itemRepository;
        }

        protected override void HandleCore(TraverseRuleDataDomainEvent notification)
        {
            var rule = notification.SynchronizeRule;
            var ruleDataList = rule.RuleDataList;
            foreach (var ruleDataItem in ruleDataList)
            {
                rule.CurrentRuleDataItem = ruleDataItem;
                var ruleItemFilter = rule.RuleItemFilterTemplate;
                if (rule.RuleProjection != null && rule.RuleProjection.Any())
                {
                    foreach (var project in rule.RuleProjection)
                    {
                        var place = $"${project}";
                        ruleItemFilter = ruleItemFilter.Replace(place,
                            ruleDataItem[project].ToString());
                    }
                }

                rule.CurrentRuleItemFilter = ruleItemFilter;
                rule.RuleItemFilterList.Add(ruleItemFilter);

                var ruleItem = rule.RuleItemList.Find(t => t.JsonFilter == ruleItemFilter);
                if (ruleItem == null)
                {
                    rule.AddItem();
                }
                else
                {
                    if (!ruleItem.Enabled)
                    {
                        ruleItem.Enabled = true;
                        ruleItem.State = SyncState.Idle;
                        _itemRepository.Update(ruleItem.Identity, ruleItem);
                    }
                }
            }

            var ruleItemList = rule.RuleItemList;

            foreach (var ruleItem in ruleItemList)
            {
                if (!rule.RuleItemFilterList.Contains(ruleItem.JsonFilter))
                {
                    rule.RemoveItem(ruleItem);
                }
            }
        }
    }
}